package com.ruoyi.business.service.impl;

import cn.hutool.log.Log;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.ruoyi.business.domain.TRecipientInfo;
import com.ruoyi.business.response.ErrorResponseData;
import com.ruoyi.business.response.ResponseData;
import com.ruoyi.business.response.SuccessResponseData;
import com.ruoyi.business.service.ITRecipientInfoService;
import com.ruoyi.business.service.LoginService;
import com.ruoyi.common.utils.HttpResponse;
import com.ruoyi.common.utils.HttpUtils;
import com.ruoyi.common.utils.UrlUtils;
import com.ruoyi.common.utils.cxzfpay.RSA2Utils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.net.URLDecoder;
import java.util.HashMap;
import java.util.List;

/**
 * 功能描述
 *
 * @author: scott
 * @date: 2022年07月04日 6:26
 */
@Service
public class LoginImpl implements LoginService {
    Log logger = Log.get();
    @Resource
    private ITRecipientInfoService recipientInfoService;
    @Override
    public ResponseData cezlogin(TRecipientInfo recipientInfo){

        String accountJson = recipientInfo.getAccountJson();
        JSONObject accountObj = JSONObject.parseObject(accountJson);
        JSONObject cookieObj = new JSONObject();
        String passport = recipientInfo.getChannelAccount().split("_")[0];

        //https://www.shouyinbei.net/api/userInfo/13950341396/Ldw834391
        String url = "https://e.o2obest.cn/api/user/shihuaAppLogin";
        HashMap dataMap = new HashMap<>();
        HashMap headerMap = new HashMap<>();

        dataMap.put("CyLoginForm[client]", "ios");
        dataMap.put("CyLoginForm[password]", "dSQGdwQMAAA=");
        dataMap.put("CyLoginForm[rememberMe]", "1");
        dataMap.put("CyLoginForm[username]", passport);
        dataMap.put("ajax", "1");
        dataMap.put("companyKey", "874d8c821358a5e26f2524b10f43a292");
        dataMap.put("en", "1");
        dataMap.put("version", "3.4.0");
        StringBuilder buf = new StringBuilder("");
        HttpUtils.buildPayParams(buf, dataMap);
        String preStr = buf.toString();
        logger.info("车E族登录请求参数：" + preStr);
        HttpResponse loginHttpResponse = HttpUtils.httpFormPost(url, headerMap, "", dataMap, "车E族登录", "");
        JSONObject resultObj = JSONObject.parseObject(loginHttpResponse.getDocument().body().text());
        logger.info("车E族登录返回:" + resultObj);
        if (!resultObj.getString("code").equalsIgnoreCase("00000")) {
            return new ErrorResponseData(-100, "登录失败，请重试");
        }
        String cookie = loginHttpResponse.getCookie();
        JSONObject data = resultObj.getJSONObject("data");
        String token = data.getString("token");
        String cezToken = data.getString("cezToken");
        cookieObj.put("token", token);
        cookieObj.put("cezToken", cezToken);
        cookieObj.put("cookie",cookie);
        headerMap.put("cookie",cookie);
        url = "https://e.o2obest.cn/api/headICRecharge/recharge?ajax=1&cezToken="+cezToken+"&companyKey=874d8c821358a5e26f2524b10f43a292&token="+token+"&version=3.4.0)";
        loginHttpResponse = HttpUtils.httpFormGet(url,headerMap,"","");
        resultObj = JSONObject.parseObject(loginHttpResponse.getBody());
        if (!resultObj.getString("code").equals("00000")) {
            return new ErrorResponseData(-100, "登录失败");
        }
        JSONArray storList = resultObj.getJSONObject("data").getJSONArray("icList");
        for (int i = 0; i < storList.size(); i++) {
            JSONObject merObj = storList.getJSONObject(i);
            TRecipientInfo query = new TRecipientInfo();
            cookieObj.put("cardNo", merObj.getString("cardNo"));
            query.setChannelAccount(passport + "_" + merObj.getString("cardNo"));
            query.setChannel("alipay_cez_h5");
            List<TRecipientInfo> recipientInfoList = recipientInfoService.selectTRecipientInfoList(query);
            logger.info("车E族列表数量："+recipientInfoList.size());
            if (recipientInfoList.size() == 0) {
                if(i==0){
                    recipientInfo.setChannelAccount(passport + "_" + merObj.getString("cardNo"));
                    recipientInfo.setOnline(1);
                    recipientInfo.setCookie(cookieObj.toJSONString());
                    recipientInfoService.updateTRecipientInfo(recipientInfo);
                }else{
                    TRecipientInfo newRecipientInfo = new TRecipientInfo();
                    BeanUtils.copyProperties(recipientInfo, newRecipientInfo);
                    newRecipientInfo.setId(null);
                    newRecipientInfo.setChannelAccount(passport + "_" + merObj.getString("cardNo"));
                    newRecipientInfo.setOnline(1);
                    recipientInfoService.insertTRecipientInfo(newRecipientInfo);
                }
            } else {
                TRecipientInfo recipientInfo1 = recipientInfoList.get(0);
                recipientInfo1.setOnline(1);
                recipientInfo1.setCookie(cookieObj.toJSONString());
                recipientInfoService.updateTRecipientInfo(recipientInfo1);
            }
        }
        return new SuccessResponseData();
    }

    @Override
    public ResponseData eftlogin(TRecipientInfo recipientInfo){

        String accountJson = recipientInfo.getAccountJson();
        JSONObject accountObj = JSONObject.parseObject(accountJson);
        JSONObject cookieObj = new JSONObject();
        HashMap dataMap = new HashMap<>();
        HashMap headerMap = new HashMap<>();
        //https://www.shouyinbei.net/api/userInfo/13950341396/Ldw834391
        String url = "https://mposapi.bjmymf.com/api/Login/GetToken";
        HttpResponse httpResponse = HttpUtils.httpFormPost(url, headerMap, "", new HashMap<>(), "诚享支付获取token", "");
        JSONObject resultObj = JSONObject.parseObject(httpResponse.getDocument().body().text());

        if (resultObj.getIntValue("code") != 0) {
            return new ErrorResponseData(-100, "登录失败");
        }

        JSONObject data = resultObj.getJSONObject("data");
        String token = data.getString("token");
        cookieObj.put("token", token);
        String passport = recipientInfo.getChannelAccount().split("_")[0];
        headerMap = new HashMap<>();
        headerMap.put("rsades", "public");
        headerMap.put("Token", token);
        JSONObject loginReq = new JSONObject();
        loginReq.put("MobileNumber", passport);
        loginReq.put("LoginPwd", accountObj.getString("password"));
        String loginStr = loginReq.toJSONString();
        String publickey = "MIGdMA0GCSqGSIb3DQEBAQUAA4GLADCBhwKBgQCPsTMt7RWswNBcA+ziiYJkgX9fepBNHJTSlEnI7IrRXK7LZDTlavjYVkdB6HlRa/ljpEeEJ4XOVJb1wjyrMfHby94cAMBnS/ZG7a/5xcA8mYWTFRsO1d49NCvPNvrIwsL8zE87cNEPHfZmVr38Y3mKtsMsfeSnsFoghz0QFqxGRQIBAw==";
        RSA2Utils rsa2Util = new RSA2Utils();
        String loginReqStr = rsa2Util.encrypt(loginStr, publickey);
        url = "https://mposapi.bjmymf.com/api/Login/PCLogin";
        String loginRes = HttpUtils.sendJsonMessage(url, headerMap, loginReqStr);
        JSONObject loginResObj = JSONObject.parseObject(loginRes);
        if (loginResObj.getIntValue("code") != 0) {
            return new ErrorResponseData(-100, "登录失败");
        }

        //获取其他标签
        url = "https://mposapivj.bjmymf.com/api/Merchant/GetLabelListByType";
        headerMap = new HashMap<>();
        headerMap.put("token", token);
        JSONObject reqObj = new JSONObject();
        reqObj.put("queryType","1");
        String labelListStr = HttpUtils.sendJsonMessage(url, headerMap, reqObj.toJSONString());
        JSONObject labeObj = JSONObject.parseObject(labelListStr);
        if(labeObj.getIntValue("code")!=0){
            return new ErrorResponseData(-100, "登录失败");
        }
        JSONArray labelArray = labeObj.getJSONArray("rows");
        for(int i=0;i<labelArray.size();i++){
            JSONObject labelInfo = (JSONObject) labelArray.get(i);
            if(labelInfo.getIntValue("status")!=3){
                continue;
            }
            TRecipientInfo query = new TRecipientInfo();
            query.setChannelAccount(passport + "_" + labelInfo.getString("merchantName"));
            query.setChannel("alipay_eft_h5");
            List<TRecipientInfo> recipientInfoList = recipientInfoService.selectTRecipientInfoList(query);
            cookieObj.put("jhxwsh_id", labelInfo.getString("id"));
            if (recipientInfoList.size() == 0) {
                if (i == 0) {
                    recipientInfo.setOnline(1);
                    recipientInfo.setCookie(cookieObj.toJSONString());
                    recipientInfo.setChannelAccount(passport + "_" + labelInfo.getString("merchantName"));
                    recipientInfoService.updateTRecipientInfo(recipientInfo);
                } else {
                    TRecipientInfo newRecipientInfo = new TRecipientInfo();
                    BeanUtils.copyProperties(recipientInfo, newRecipientInfo);
                    newRecipientInfo.setId(null);
                    recipientInfo.setCookie(cookieObj.toJSONString());
                    newRecipientInfo.setChannelAccount(passport + "_" + labelInfo.getString("merchantName"));
                    newRecipientInfo.setOnline(1);
                    recipientInfoService.insertTRecipientInfo(newRecipientInfo);
                }
            }else{
                TRecipientInfo recipientInfo1 = recipientInfoList.get(0);
                recipientInfo1.setOnline(1);
                recipientInfo1.setCookie(cookieObj.toJSONString());
                recipientInfoService.updateTRecipientInfo(recipientInfo1);
            }
        }
        return new SuccessResponseData();
    }

    @Override
    public ResponseData cxzflogin(TRecipientInfo recipientInfo) {
        String accountJson = recipientInfo.getAccountJson();
        JSONObject accountObj = JSONObject.parseObject(accountJson);
        JSONObject cookieObj = new JSONObject();
        HashMap dataMap = new HashMap<>();
        HashMap headerMap = new HashMap<>();
        //https://www.shouyinbei.net/api/userInfo/13950341396/Ldw834391
        String url = "https://cxzfapi.bjmymf.com/api/Login/GetToken";
        HttpResponse httpResponse = HttpUtils.httpFormPost(url, headerMap, "", new HashMap<>(), "诚享支付获取token", "");
        JSONObject resultObj = JSONObject.parseObject(httpResponse.getDocument().body().text());
        logger.info("登录GetToken返回："+resultObj);

        if (resultObj.getIntValue("code") != 0) {
            return new ErrorResponseData(-100, "登录失败");
        }

        JSONObject data = resultObj.getJSONObject("data");
        String token = data.getString("token");
        cookieObj.put("token", token);
        String passport = recipientInfo.getChannelAccount().split("_")[0];
        headerMap = new HashMap<>();
        headerMap.put("rsades", "public");
        headerMap.put("Token", token);
        JSONObject loginReq = new JSONObject();
        loginReq.put("MobileNumber", passport);
        loginReq.put("LoginPwd", accountObj.getString("password"));
        String loginStr = loginReq.toJSONString();
        String publickey = "MIGdMA0GCSqGSIb3DQEBAQUAA4GLADCBhwKBgQCPsTMt7RWswNBcA+ziiYJkgX9fepBNHJTSlEnI7IrRXK7LZDTlavjYVkdB6HlRa/ljpEeEJ4XOVJb1wjyrMfHby94cAMBnS/ZG7a/5xcA8mYWTFRsO1d49NCvPNvrIwsL8zE87cNEPHfZmVr38Y3mKtsMsfeSnsFoghz0QFqxGRQIBAw==";
        RSA2Utils rsa2Util = new RSA2Utils();
        String loginReqStr = rsa2Util.encrypt(loginStr, publickey);
        url = "https://cxzfapi.bjmymf.com/api/Login/PCLogin";
        String loginRes = HttpUtils.sendJsonMessage(url, headerMap, loginReqStr);
        JSONObject loginResObj = JSONObject.parseObject(loginRes);
        logger.info("登录PCLogin返回："+loginResObj);

        if (loginResObj.getIntValue("code") != 0) {
            return new ErrorResponseData(-100, "登录失败");
        }
        url = "https://cxzfvjapi.bjmymf.com/api/APPUser/GetPayTagExtList";
        headerMap = new HashMap<>();
        headerMap.put("token",token);
        JSONObject jhxwshIdReqObj = new JSONObject();
        jhxwshIdReqObj.put("jhxwshId",1);
        String jhxwshIdStr = HttpUtils.sendJsonMessage(url,headerMap,jhxwshIdReqObj.toJSONString());
        JSONObject jhxwshIdResObj = JSONObject.parseObject(jhxwshIdStr);
        logger.info("GetPayTagExtList返回："+jhxwshIdResObj);

        if(jhxwshIdResObj.getIntValue("code")!=0){
            return new ErrorResponseData(-100, "登录失败："+jhxwshIdResObj.getString("msg"));
        }
        JSONArray jhxwshIdDataList = jhxwshIdResObj.getJSONObject("data").getJSONArray("list");

        for(int i=0;i<jhxwshIdDataList.size();i++){
            JSONObject jhxwshIdData =jhxwshIdDataList.getJSONObject(i);
            String jhxwshIdDataUrl = jhxwshIdData.getString("payTagUrl");
//            JSONArray labelArray = labeObj.getJSONArray("rows");
//            JSONObject labelInfo = (JSONObject) labelArray.get(i);
            if(jhxwshIdData.getIntValue("status")!=1){
                continue;
            }
            TRecipientInfo query = new TRecipientInfo();
            query.setChannelAccount(passport + "_" + jhxwshIdData.getString("payTagName"));
            query.setChannel("alipay_cxzf_h5");
            List<TRecipientInfo> recipientInfoList = recipientInfoService.selectTRecipientInfoList(query);
            cookieObj.put("payTagUrl", jhxwshIdDataUrl);
            if (recipientInfoList.size() == 0) {
                if (i == 0) {
                    recipientInfo.setOnline(1);
                    recipientInfo.setCookie(cookieObj.toJSONString());
                    recipientInfo.setChannelAccount(passport + "_" + jhxwshIdData.getString("payTagName"));
                    recipientInfoService.updateTRecipientInfo(recipientInfo);
                } else {
                    TRecipientInfo newRecipientInfo = new TRecipientInfo();
                    BeanUtils.copyProperties(recipientInfo, newRecipientInfo);
                    newRecipientInfo.setId(null);
                    recipientInfo.setCookie(cookieObj.toJSONString());
                    newRecipientInfo.setChannelAccount(passport + "_" + jhxwshIdData.getString("payTagName"));
                    newRecipientInfo.setOnline(1);
                    recipientInfoService.insertTRecipientInfo(newRecipientInfo);
                }
            }else{
                TRecipientInfo recipientInfo1 = recipientInfoList.get(0);
                recipientInfo1.setOnline(1);
                recipientInfo1.setCookie(cookieObj.toJSONString());
                recipientInfoService.updateTRecipientInfo(recipientInfo1);
            }
        }
        return new SuccessResponseData();
    }

    @Override
    public ResponseData kmtlogin(TRecipientInfo recipientInfo, String vercode,String vercodeRandomStr) {
        String accountJson = recipientInfo.getAccountJson();
        JSONObject accountObj = JSONObject.parseObject(accountJson);
        JSONObject cookieObj = new JSONObject();
        HashMap<String,String> dataMap = new HashMap<>();
        HashMap<String,String> headerMap = new HashMap<>();
        String passport = recipientInfo.getChannelAccount().split("_")[0];
        //https://mch.52pay.com/api/auth?loginType=web&vercodeRandomStr=Ccn3FX1702584759353&username=13950341396&password=Pwd830121&vercode=279460&googleCode=
        headerMap.put("referer","https://servicewechat.com/wx6541b67849efb946/16/page-frame.html");
        headerMap.put("User-Agent","Mozilla/5.0 (iPhone; CPU iPhone OS 17_1_2 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Mobile/15E148 MicroMessenger/8.0.44(0x18002c2f) NetType/WIFI Language/zh_CN");
        String url = "https://mch.f.52pay.com/api/auth?&username="+passport+"&password="+accountObj.getString("password")+"&loginType=uni-app&googleCode=";
        HttpResponse httpResponse = HttpUtils.httpGet(url, headerMap,"",  "快米兔登录");
        JSONObject resultObj = JSONObject.parseObject(httpResponse.getBody());
        logger.info("登录GetToken返回："+resultObj);
        if (resultObj.getIntValue("code") != 0) {
            return new ErrorResponseData(-100, "登录失败");
        }
        JSONObject data = resultObj.getJSONObject("data");
        String token = data.getString("access_token");
        cookieObj.put("token", token);
        cookieObj.put("storeName", data.getString("storeName"));
        cookieObj.put("storeId", data.getString("storeId"));

        url = "https://mch.f.52pay.com/api/mch_qrcode/list";
        headerMap.put("Authorization",token);
        dataMap = new HashMap<>();
        dataMap.put("page","1");
        dataMap.put("limit","10");
        dataMap.put("payAmount","");
        HttpResponse merListResp = HttpUtils.httpFormPost(url,headerMap,"",dataMap,"","");
        JSONObject merListRespObj = JSONObject.parseObject(merListResp.getBody());
        logger.info("mch_qrcode返回："+merListRespObj);

        if(merListRespObj.getIntValue("code")!=0){
            return new ErrorResponseData(-100, "登录失败："+merListRespObj.getString("msg"));
        }
        JSONArray jhxwshIdDataList = merListRespObj.getJSONArray("data");

        for(int i=0;i<jhxwshIdDataList.size();i++){
            JSONObject jhxwshIdData =jhxwshIdDataList.getJSONObject(i);
            String imgurl = jhxwshIdData.getString("url");
            UrlUtils.UrlEntity urlEntity = UrlUtils.parse(imgurl);
            String jhxwshIdDataUrl = URLDecoder.decode(urlEntity.params.get("url"));
//            JSONArray labelArray = labeObj.getJSONArray("rows");
//            JSONObject labelInfo = (JSONObject) labelArray.get(i);
            if(jhxwshIdData.getIntValue("status")!=1){
                continue;
            }
            cookieObj.put("storeName", jhxwshIdData.getString("storeName"));
            cookieObj.put("storeId", jhxwshIdData.getString("storeId"));
            cookieObj.put("operatorId", jhxwshIdData.getString("operatorId"));

            TRecipientInfo query = new TRecipientInfo();
            query.setChannelAccount(passport + "_" + jhxwshIdData.getString("codeName"));
            query.setChannel("alipay_kmt_h5");
            List<TRecipientInfo> recipientInfoList = recipientInfoService.selectTRecipientInfoList(query);
            if (recipientInfoList.size() == 0) {
                if (i == 0) {
                    recipientInfo.setOnline(1);
                    recipientInfo.setCookie(cookieObj.toJSONString());
                    recipientInfo.setReceiptQrcode(jhxwshIdDataUrl);
                    recipientInfo.setChannelAccount(passport + "_" + jhxwshIdData.getString("codeName"));
                    recipientInfoService.updateTRecipientInfo(recipientInfo);
                } else {
                    TRecipientInfo newRecipientInfo = new TRecipientInfo();
                    BeanUtils.copyProperties(recipientInfo, newRecipientInfo);
                    newRecipientInfo.setId(null);
                    recipientInfo.setCookie(cookieObj.toJSONString());
                    recipientInfo.setReceiptQrcode(jhxwshIdDataUrl);
                    newRecipientInfo.setChannelAccount(passport + "_" + jhxwshIdData.getString("codeName"));
                    newRecipientInfo.setOnline(1);
                    recipientInfoService.insertTRecipientInfo(newRecipientInfo);
                }
            }else{
                TRecipientInfo recipientInfo1 = recipientInfoList.get(0);
                recipientInfo1.setOnline(1);
                recipientInfo1.setCookie(cookieObj.toJSONString());
                recipientInfo.setReceiptQrcode(jhxwshIdDataUrl);
                recipientInfoService.updateTRecipientInfo(recipientInfo1);
            }
        }
        recipientInfo.setOnline(1);
        recipientInfo.setCookie(cookieObj.toJSONString());
        recipientInfoService.updateTRecipientInfo(recipientInfo);
        return new SuccessResponseData();
    }



}
